package ar.com.android.alco.adapters;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import ar.com.android.alco.entities.Alimentos;
import ar.com.android.alco.forms.R;

public class AutoCompleteAlimentoAdapter extends ArrayAdapter<Alimentos> implements Filterable {

	Activity activity;
	public List<Alimentos> alimentos;
	private AlimentoFilter filter;
	List<Alimentos> origAlimentos;
	
	public AutoCompleteAlimentoAdapter(Activity activity, int textViewResourceId, List<Alimentos> alimentos)
	{
		super(activity, textViewResourceId, alimentos);
		this.activity = activity;
		this.alimentos = alimentos;
		filter = new AlimentoFilter();
	}
	
	@Override
	public int getCount() {
		if(alimentos != null)
			return alimentos.size();
		else
			return 0;
	}

	@Override
	public Alimentos getItem(int position) {
		return alimentos.get(position);
	}

	@Override
	public long getItemId(int position) {
		return alimentos.get(position).getIdAlimento();
	}
	
	private class AlimentoView
	{
		TextView tvAlimento;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		AlimentoView fv;
		LayoutInflater inflater =  activity.getLayoutInflater();
		
		if(convertView == null)
		{
			convertView = inflater.inflate(R.drawable.tv_alimento, null);
			fv = new AlimentoView();
			fv.tvAlimento = (TextView) convertView.findViewById(R.id.tvAlimento);
			
			convertView.setTag(fv);
		}
		else
			fv = (AlimentoView) convertView.getTag();
		
		fv.tvAlimento.setText(alimentos.get(position).toString());
		
		return convertView;
	}

	@Override
	public Filter getFilter() {
		return filter;
	}
	
	private class AlimentoFilter extends Filter
	{

		@Override
		protected FilterResults performFiltering(CharSequence constraint) {
			FilterResults oReturn = new FilterResults();
			List<Alimentos> results = new ArrayList<Alimentos>();
			if(origAlimentos == null)
				origAlimentos = alimentos;
			
			 if (constraint != null)
			 {
				 if (origAlimentos != null && origAlimentos.size() > 0) {                     
					 for (Alimentos alimento : origAlimentos) {                            
						 if (alimento.getDescripcion().toUpperCase().contains(constraint.toString().toUpperCase()))   
							 results.add(alimento);
					 }
				 }
				 oReturn.values = results;
			 }
			return oReturn;
		}

		
		@SuppressWarnings("unchecked")
		@Override
		protected void publishResults(CharSequence constraint, FilterResults results) {
			alimentos = (List<Alimentos>) results.values;
			notifyDataSetChanged();
		}
		
	}

}
